var constant = require('../../../../../framework/constant');
var util = require('../../../../../framework/util');
var mongoose = require('../../../../../framework/mongoose');
var CmmImage = require('../../../../../framework/model/image').CmmImage;

var CmsStore = require('./model').CmsStore;
var CmsStoreCategory = require('./model').CmsStoreCategory;
var CmsStoreProduct = require('./model').CmsStoreProduct;

var service = require('./service');

//Rest Interface
exports.queryStoreBySubId = function (req, res) {
    var pageSize = req.query.pageSize;
    var page = req.query.page;

    CmsStore.find({subscription: req.query.subId}).sort('order').exec(function (err, stores) {
        var conditions = {store: stores[0].id};
        if (!!pageSize) {
            CmsStoreCategory.count(conditions, function(err, cnt) {
                CmsStoreCategory
                    .find(conditions)
                    .sort({updateTime: 'desc'})
                    .limit(pageSize)
                    .skip((page - 1) * pageSize)
                    .exec(function (err, cates) {
                        var code = pageSize * page >= cnt?constant.HTTP_RETURN_CODE_NO_MORE: constant.HTTP_RETURN_CODE_SUCCESS;
                        res.send({code: code, data: {store: stores[0], categories: cates}});
                    }
                );
            });
        } else {
            CmsStoreCategory
                .find(conditions)
                .sort({updateTime: 'desc'})
                .exec(function (err, cates) {
                    res.send({code: constant.HTTP_RETURN_CODE_SUCCESS, data: {store: stores[0], categories: cates}});
                });
        }

    });
};
exports.storeById = function(req, res){
    mongoose.findById(CmsStore, req.params.id, function(store) {
        res.send({data: store});
    });
};
exports.saveStore = function (req, res) {
    var store = new CmsStore({
        name: req.body.name,
        descr: req.body.descr,
        updateTime: new Date()
    });
    store.save(function(){
        return res.send({code: 1, data: store});
    });
};
exports.updateStore = function(req, res){
    CmsStore.findByIdAndUpdate(
        req.params.id,
        {
            name: req.body.store.name,
            descr: req.body.store.descr,
            updateTime: new Date()
        }, function(){
            return res.send({code: 1});
        }
    )
};
exports.deleteStore = function(req, res){
    CmsStore.findByIdAndRemove(req.params.id, function(){
        return res.send({code: 1});
    })
};

exports.categoryById = function(req, res){
    mongoose.findById(CmsStoreCategory, req.params.id, function(cate) {
        res.send({data: cate});
    });
};
exports.saveCategory = function (req, res) {
    var storeCategory = new CmsStoreCategory({
        name: req.body.name,
        descr: req.body.descr,
        image: req.body.image,
        store: req.body.storeId,
        updateTime: new Date()
    });

    storeCategory.save(function(){
        return res.send({code: 1, data: storeCategory});
    });
};
exports.updateCategory = function(req, res){
    CmsStoreCategory.findByIdAndUpdate(
        req.params.id,
        {
            name: req.body.name,
            descr: req.body.descr,
            image: req.body.image,
            store: req.body.store,
            updateTime: new Date()
        }, function(){
            res.send({code: 1});
        }
    )
};
exports.deleteCategory = function(req, res){
    CmsStoreCategory.findByIdAndRemove(req.params.id, function(){
        return res.send({code: 1});
    })
};

exports.queryProductByCategoryId = function(req, res){
    var pageSize = req.query.pageSize;
    var page = req.query.page;
    var conditions = {category: req.query.categoryId};
    if (!!pageSize) {
        CmsStoreProduct.count(conditions, function(err, cnt) {
            CmsStoreProduct
                .find(conditions)
                .sort({updateTime: 'desc'})
                .limit(pageSize)
                .skip((page - 1) * pageSize)
                .exec(function (err, products) {
                        var code = pageSize * page >= cnt?constant.HTTP_RETURN_CODE_NO_MORE: constant.HTTP_RETURN_CODE_SUCCESS;
                        CmsStoreProduct.populate(products, { path: 'images' }, function (err, products) {
                            res.send({code: code, data: {products: products}});
                        });
                })
        });
    }
    else {
        CmsStoreProduct
            .find(conditions)
            .sort({updateTime: 'desc'})
            .exec(function (err, products) {
                CmsStoreProduct.populate(products, { path: 'images' }, function (err, products) {
                    res.send({code: constant.HTTP_RETURN_CODE_SUCCESS, data: {products: products}});
                });
            })
    }
};
exports.productById = function(req, res){
    mongoose.findById(CmsStoreProduct, req.params.id, function(product) {
        res.send({data: product});
    });
};
exports.saveProduct = function (req, res) {
    var categoryId = req.body.categoryId;
    var images = req.body.images;

    var storeProduct = new CmsStoreProduct({
        name: req.body.name,
        descr: req.body.descr,
//        price: req.body.price,
//        freight: req.body.freight,
//        flatRate: req.body.flatRate,
        thumb: images[0].thumbnailUrl,
        status: 1,
        updateTime: new Date(),
        category: categoryId
    });

    var imageList = [];
    for(var i = 0; i < images.length; i++) {
        imageList[i] = {parentId: storeProduct._id, url: images [i].url};
    }

    CmmImage.create(imageList, function (err) {
        for (var i=1; i < arguments.length; i++) {
            if (arguments[i] != null) {
                storeProduct.images.push(arguments[i]);
            }
        }
        storeProduct.save(function(){
            var data = {code: 1};
            res.send(data);
        });
    });
};
exports.updateProduct = function(req, res){
    var category = req.body.category;
    var images = req.body.images;

    CmsStoreProduct.findById(req.params.id, function (err, storeProduct) {
        storeProduct.name = req.body.name;
        storeProduct.descr = req.body.descr;
//        storeProduct.price = req.body.price;
//        storeProduct.freight = req.body.freight;
//        storeProduct.flatRate = req.body.flatRate;
        storeProduct.thumb = images[0].thumbnailUrl;
        storeProduct.status = 1;
        storeProduct.updateTime = new Date();

        var imageList = [];
        for(var i = 0; i < images.length; i++) {
            imageList[i] = {parentId: storeProduct._id, url: images [i].url};
        }

        CmmImage.create(imageList, function (err) {
            storeProduct.images = [];
            for (var i=1; i < arguments.length; i++) {
                if (arguments[i] != null) {
                    storeProduct.images.push(arguments[i]);
                }
            }
            storeProduct.save(function(){
                var data = {code: 1};
                res.send(data);
            });
        });
    });
};
exports.deleteProduct = function(req, res){
    CmsStoreProduct.findByIdAndRemove(req.params.id, function(){
        return res.send({code: 1});
    })
};